import {Form, message} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText, ProFormTextArea,
} from '@ant-design/pro-form';
import {isEmpty, isSuccess} from "@/utils/utils";
import {OpAgreement} from "@/services/api-functions";
import BraftEditor from "braft-editor";
import 'braft-editor/dist/index.css'
import {AgreementModRequest} from "@/services/api-types";

const handleEdit = async (fields: any, select: any, content: string) => {
  try {
    if(isEmpty(content)){message.error('请输入内容'); return false}
    const rpo: AgreementModRequest = {
      id: select?.id ?? '',
      title: fields.title??'',
      remark: fields.remark ?? '',
      content
    }
    if (isSuccess(((await OpAgreement.agreementMod(rpo))?.code))) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};


const AgreementList: React.FC<any> = () => {

  const [formRef] = Form.useForm()
  const [visible, handleVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [editorState, setEditorState] = useState<any>(BraftEditor.createEditorState("")) // 存储 editor 实例
  const initFiledValue = (id: any = undefined, callBack: Function) => {
    if (id) {
      OpAgreement.agreementDetail(id).then(({code, data}) => {
        if (isSuccess(code)) {
          formRef?.setFieldsValue({
            title: data.title,
            remark: data.remark,
          })
          setEditorState(BraftEditor.createEditorState(data?.content ?? ''))
          if (callBack) {
            callBack()
          }
        }
      })
    }
  }

  const columns: ProColumns[] = [
    {
      title: 'CODE',
      dataIndex: 'code',
      hideInSearch: true,
      ellipsis: true,
      fixed: 'left',
    },
    {
      title: '标题',
      dataIndex: 'title',
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 300,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '版本',
      dataIndex: 'version',
      width: 200,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '操作者',
      dataIndex: 'operateName',
      width: 150,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        <a key="edit"
           onClick={() => {
             setCurrentRow(record)
             initFiledValue(record.id, () => handleVisible(true))
           }}
        >编辑</a>
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<any, any>
        headerTitle='协议列表'
        actionRef={actionRef}
        rowKey="id"
        search={{labelWidth: 120,}}
        toolBarRender={() => []}
        request={async (params) => {

          const {data: {data, total}, code}: any = await OpAgreement.agreementList(params);

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />
      <ModalForm
        title={`编辑【${currentRow?.title}】`}
        width="750px"
        form={formRef}
        visible={visible}
        onVisibleChange={v => {
          handleVisible(v)
          if (!v) {
            formRef?.resetFields()
            setEditorState(BraftEditor.createEditorState( ''))
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await handleEdit(value as any, currentRow, editorState?.toHTML()??'')) {
            handleVisible(false);
            formRef?.resetFields()
            setEditorState(BraftEditor.createEditorState( ''))
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText label='标题' required rules={[{required: true, message: '请填写标题',},]} name="title"/>
        <ProFormTextArea label='备注' name="remark"/>
        <Form.Item label='内容'>
          <BraftEditor
            value={editorState}
            onChange={state => setEditorState(state)}
          />
        </Form.Item>
      </ModalForm>
    </PageContainer>
  );
};

export default AgreementList;
